package bb.lanxing.activity.login

import android.content.Intent
import android.graphics.Color
import android.os.CountDownTimer
import android.util.Log
import android.widget.Toast
import bb.lanxing.App
import bb.lanxing.R
import bb.lanxing.activity.interfaces.IGetAuthCodeView
import bb.lanxing.common.config.Constants.INTERVAL_1_MIN
import bb.lanxing.databinding.ActivityLogoutIdentifyBinding
import bb.lanxing.manager.SharedManager
import bb.lanxing.mvp.presetner.GetAuthCodePresenterImpl
import bb.lanxing.mvp.presetner.i.IGetAuthCodePresenter
import bb.lanxing.mvvm.base.BaseDBActivity
import org.json.JSONObject
import kotlin.jvm.internal.Intrinsics

class LogoutIdentifyActivity : BaseDBActivity<ActivityLogoutIdentifyBinding>(), IGetAuthCodeView {
    private var phone: String? = null
    private var timer: CountDownTimer? = null
    private lateinit var presenter: IGetAuthCodePresenter
    override fun getLayoutId(): Int {
        return R.layout.activity_logout_identify
    }

    override fun initView(binding: ActivityLogoutIdentifyBinding) {
        setTitle(R.string.st_identify_phone)
        setupActionBar(true)
        presenter = GetAuthCodePresenterImpl(this)
        val userPhone = App.getContext().userPhone
        phone = userPhone
        val textView = binding.txtPhoneNumLogout
        phone?.let {
            textView.text = getString(R.string.user_logout_send_code) + changPhoneNumber(it)
        }
        binding.pinEntry.setAnimateText(true)
        binding.pinEntry.setOnPinEnteredListener { charSequence: CharSequence ->
            if (charSequence.length == 6) {
                binding.confirmButtonLogout.setBackgroundResource(R.drawable.ring_2dip_no_side_blue)
                binding.confirmButtonLogout.isClickable = true
                verifyMSgCode(charSequence.toString())
            }
        }
        val lastSendTS = SharedManager.getInstance().getLogoutTime(phone)
        Log.e("lastTIme", lastSendTS.toString())
        if (lastSendTS == null || lastSendTS != 0L) {
            val currentTimeMillis = System.currentTimeMillis()
            Intrinsics.checkNotNullExpressionValue(lastSendTS, "lastSendTS")
            if (currentTimeMillis - lastSendTS!! <= 6000) {
                val currentTimeMillis2 = 6000 - (System.currentTimeMillis() - lastSendTS)
                Log.e("remainTime", currentTimeMillis2.toString())
                startTimer(currentTimeMillis2)
                binding.txtSendLogout.setOnClickListener { sendVerifyCode() }
            }
        }
        sendVerifyCode()
        binding.txtSendLogout.setOnClickListener { sendVerifyCode() }
        binding.confirmButtonLogout.setOnClickListener {
            // TODO: 假的,简单对比
            if (binding.pinEntry.text.toString() == "123456") {
                Toast.makeText(this, R.string.st_identify_phone_success, Toast.LENGTH_SHORT).show()
                startActivity(Intent(this, LogoutConfirmActivity::class.java))
            } else {
                Toast.makeText(this, R.string.st_identify_phone_fail, Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun sendVerifyCode() {
        val str = phone
        if (str.isNullOrEmpty()) {
            Toast.makeText(this, R.string.st_identify_phone_num_not_found, Toast.LENGTH_SHORT)
                .show()
            finish()
        }
        presenter.getAuthCode(phone, 0, 0)
    }

    private fun verifyMSgCode(str: String) {
//        Observable.create(new NetSubscribe(BiciHttpClient.requestVerifyLogoutMsg(str))).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread
//        ()).subscribe(new LogoutIdentifyActivity$VerifyMSgCode$1(this));
    }

    private fun startTimer(j: Long) {
        val textView = binding.txtSendLogout
        textView.isEnabled = false
        textView.setTextColor(Color.parseColor("#333333"))
        if (timer == null) {
            timer = object : CountDownTimer(j, 1000L) {
                override fun onTick(j2: Long) {
                    textView.text = getString(R.string.user_logout_send_code_retry) + "(" + (j2 / 1000) + "s)"
                }

                override fun onFinish() {
                    textView.isEnabled = true
                    textView.text = getString(R.string.user_logout_send_code_retry)
                    textView.setTextColor(Color.parseColor("#FF0000"))
                }
            }
        }
        timer?.start()
    }

    private fun changPhoneNumber(str: String): String {
//        val stringBuffer = StringBuffer()
//        if (str.length > 10) {
//            val substring: String = str.substring(0, 3)
//            Intrinsics.checkNotNullExpressionValue(substring, "this as java.lang.String…ing(startIndex, endIndex)")
//            stringBuffer.append(substring)
//            val substring2: String = str.substring(3, 7)
//            Intrinsics.checkNotNullExpressionValue(substring2, "this as java.lang.String…ing(startIndex, endIndex)")
//            stringBuffer.append(replace(substring2, substring2, "****", false, 4, null))
//            val substring3: String = str.substring(7, 11)
//            Intrinsics.checkNotNullExpressionValue(substring3, "this as java.lang.String…ing(startIndex, endIndex)")
//            stringBuffer.append(substring3)
//            val stringBuffer2 = stringBuffer.toString()
//            Intrinsics.checkNotNullExpressionValue(stringBuffer2, "{\n            val frontT…  sb.toString()\n        }")
//            return stringBuffer2
//        }
        return str
    }

    override fun onDestroy() {
        timer?.cancel()
        super.onDestroy()
    }

    override fun onGetAuthCodeResult(result: Boolean, type: Int) {
        if (result) {
            startTimer(INTERVAL_1_MIN)
        }
    }

    override fun onGetAuthCodeResult(jsonObject: JSONObject) {
    }
}
